package com.strugglerz.web.shiro;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 * 扩展 shiro 认证过滤器， 使其无缝支持 ajax 提交时，session 已经超时 302 登录不跳转
 * 
 * @author suan
 */
public class FormAuthenticationExtFilter extends FormAuthenticationFilter {

	/**
	 * 重定向至登录页面时，如果当前是异步请求，则设置 401 响应
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		HttpServletRequest req = WebUtils.toHttp(request);
		String xmlHttpRequest = req.getHeader("X-Requested-With");
		if (xmlHttpRequest != null)
			if (xmlHttpRequest.equalsIgnoreCase("XMLHttpRequest")) {
				HttpServletResponse res = WebUtils.toHttp(response);
				res.sendError(401);
				return false;
			}
		return super.onAccessDenied(request, response, mappedValue);
	}
}
